package com.example.demo.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author wan
 * @version 1.0.0
 * @Description mybatis工厂
 * @createTime 2021年08月26日 10:55:28
 */
public class SqlSessionFactoryUtil {

    private static String RESOURCE = "mybatis-config.xml";
    private static SqlSessionFactory sqlSessionFactory;
    private static SqlSession sqlSession;
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();

    /**
     * 初始化SqlSessionFactory方法
     */
    public static void initSqlSessionFactory() {
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream(RESOURCE);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("产生异常。。。。"+e.getMessage());
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    }

    /**
     * 获取session
     * @return
     */
    public static SqlSession getSqlSession() {
        sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }

    /**
     * 获取工厂方法
     * @return
     */
    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

    /**
     * 提交事务
     */
    public static void commitTransaction() {
        sqlSession.commit();
    }

    public static void close() {
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null) {
            sqlSession.close();
            threadLocal.set(null);
        }
    }
}
